import matplotlib.pyplot as plt
from tornado.web import RequestHandler
import json
import common as com
from logHandler import getLogger
from timeoutHandler import set_timeout
import os

class HistogramDto(object):
    def __init__(self, time_list, acc_score_list, title, save_path, image_name):
        self.time_list = time_list
        self.acc_score_list = acc_score_list
        self.title = title
        self.save_path = save_path
        self.image_name = image_name


def dictToHistogramDto(d):
    return HistogramDto(d["timeList"], d["accScoreList"], d["title"], d["savePath"], d["imageName"])


class HistogramHandler(RequestHandler):
    @set_timeout(com.timeoutTime)
    def post(self):
        try:
            jsonByte = self.request.body
            jsonStr = jsonByte.decode("utf-8")
            histogram_dto = json.loads(jsonStr, object_hook=dictToHistogramDto)
            log = getLogger()
            log.info("开始生成柱状图：{}".format(histogram_dto.__dict__))

            # 这两行代码解决 plt 中文显示的问题
            plt.rcParams['font.sans-serif'] = ['SimHei']
            plt.rcParams['axes.unicode_minus'] = False

            fig, ax = plt.subplots(figsize=(14, 8))
            # "derf逐日原数据acc评分"
            title = histogram_dto.title
            # time_list = ['2021-01-01', '2021-01-06', '2021-01-11', '2021-01-16', '2021-01-21', '2021-01-26',
            #              '2021-02-01', '2021-02-06', '2021-02-11', '2021-02-16', '2021-02-21', '2021-02-26',
            #              '2021-03-01', '2021-03-06', '2021-03-11', '2021-03-16', '2021-03-21', '2021-03-26']
            time_list = histogram_dto.time_list
            # 数值范围正负1，保留两位小数
            # acc_score_list = [0.75, 0.32, -0.35, 0.00, 0.15, -0.88, 0.75, 0.32, -0.35, 0.00, 0.15, -0.88, 0.75, 0.32,
            #                   -0.35, 0.00, 0.15, -0.88]
            acc_score_list = histogram_dto.acc_score_list
            plt.bar(time_list, acc_score_list, width=0.6, color='#619cff')
            plt.title(title, size=20)
            plt.xticks(fontsize=11)
            plt.yticks(fontsize=11)
            index = 0
            for value in acc_score_list:
                if value != 0:
                    if value > 0:
                        plt.text(index - 0.35, value + 0.04, "%s" % value, va='center', size=15)
                    else:
                        plt.text(index - 0.45, value - 0.04, "%s" % value, va='center', size=15)
                else:
                    plt.text(index - 0.35, value, "%s" % value, va='center', size=15)
                index += 1

            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)

            zero = [0 for i in range(len(acc_score_list))]
            ax.plot(time_list, zero, color="#cccccc")

            save_path = histogram_dto.save_path
            image_name = histogram_dto.image_name
            if os.path.exists(save_path) is False:
                os.makedirs(save_path)

            plt.savefig(save_path + image_name, bbox_inches='tight', transparent=True, pad_inches=0.5, facecolor='#FFFFFF')
            plt.clf()
            plt.close(fig)
            commonResponse = com.CommonResponse(com.successCode, com.successMsg, dict([("obj", save_path + image_name)]))
            log.info("柱状图生成完毕")
        except BaseException as e:
            commonResponse = com.CommonResponse(com.errorCode, "{}".format(e), dict([("obj", com.missingValues)]))
            log.error("柱状图生成异常：{}".format(e))
        finally:
            # 返回数据
            self.write(commonResponse.__dict__)